//
// Created by Administrator on 2023/3/18.
//

#include "buffer.h"
#include "sys/uio.h"
#include "unistd.h"
ssize_t buffer::readFd(int fd) {
    char extraBuf[65536];
    struct iovec vec[2];
    const size_t writeable = writeableBytes();
    vec[0].iov_base = beginWrite();
    vec[0].iov_len = writeable;
    vec[1].iov_base = extraBuf;
    vec[1].iov_len = sizeof extraBuf;
    const int iovcnt = (writeable < sizeof extraBuf) ? 2 : 1;
    const ssize_t n = ::readv(fd, vec, iovcnt);
    if (n < 0) {
        return n;
    } else if (static_cast<size_t>(n) <= writeable) {
        writerIndex_ += n;
    } else {
        writerIndex_ = buffer_.size();
        append(extraBuf, n - writeable);
    }

    return n;
}

ssize_t buffer::writeFd(int fd) {
    assert(fd > 5);
    ssize_t n = ::write(fd, peek(), readableBytes());
    if (n > 0) {
        retrieve(n);
    }
    return n;
}
